# -*- coding: utf-8 -*-
# Create your views here.
from django.template.loader import get_template
from django.template import RequestContext
from django.shortcuts import render_to_response
from youtu.models import Blogs,BlogType,User
from django.http import HttpResponse
import json
from django.core import serializers
from django.http import HttpResponseRedirect
from django.db.models import Q
from django.http import Http404
import os,StringIO
from PIL import Image
from datetime import *
import random
ONE_PAGE_OF_DATA = 6
def Index(rq):
    startPos,endPos,allPage,curPage,pagenum = GetPages(rq)
    article_list = Blogs.objects.order_by('-Id')[startPos:endPos]
    type_list = BlogType.objects.all()
    
    return render_to_response('index.html',{'article_list':article_list,'type_list':type_list,'allPage':allPage,'curPage':curPage,'pagenum':pagenum},context_instance=RequestContext(rq))

def GetPages(rq,select_type=None):
    try:
        curPage = int(rq.GET.get('curPage','1'))
        allPage = int(rq.GET.get('allPage','1'))
        pageType = str(rq.GET.get('pageType',''))
    except ValueError:
        curPage = 1
        allPage = 1
        pageType = ''
    if pageType == 'pageDown':
        curPage += 1
    elif pageType == 'pageUp':
        curPage -= 1
    startPos = (curPage - 1) * ONE_PAGE_OF_DATA
    endPos = startPos + ONE_PAGE_OF_DATA

    
    if curPage == 1 and allPage == 1:
        if select_type == None:
            allPostCounts = Blogs.objects.count()
        else:
            allPostCounts = Blogs.objects.filter(Type=select_type).count()
        allPage = allPostCounts / ONE_PAGE_OF_DATA
        remainPost = allPostCounts % ONE_PAGE_OF_DATA
        if remainPost > 0:
            allPage += 1
    if curPage > 3:
        startnum = curPage - 3
    else:
        startnum = 1
    if startnum + 7 < allPage:
        endnum = startnum + 7
    else:
        endnum = allPage + 1
        if endnum - 7 < 0:
            startnum = 1
        else:
            startnum = endnum - 7
    pagenum = range(startnum,endnum,1)

    return startPos,endPos,allPage,curPage,pagenum

def Blog(rq,offset):
    try:
        id = int(offset)
    except ValueError:
        raise Http404()
    singlebefore = None
    singlenext = None
    try:
        article = Blogs.objects.get(Id=id)
    except Exception:
        raise Http404()
    type_list = BlogType.objects.all()
    if Blogs.objects.filter(Type=article.Type,Id__lt=id).order_by('-Id').count() > 0:
        singlebefore = Blogs.objects.filter(Type=article.Type,Id__lt=id).order_by('-Id')[0]
    if Blogs.objects.filter(Type=article.Type,Id__gt=id).count() > 0:
        singlenext = Blogs.objects.filter(Type=article.Type,Id__gt=id)[0]

    return render_to_response('single.html',{'article':article,'type_list':type_list,'singlebefore':singlebefore,'singlenext':singlenext},context_instance=RequestContext(rq))

def About(rq):
    type_list = BlogType.objects.all()
    return render_to_response('about.html', {'type_list':type_list},context_instance=RequestContext(rq))

def Manage(rq):
    if rq.session.get('login','') != 'admin':
        username = rq.POST.get('UserName','')
        password = rq.POST.get('PassWord','')
        user = User.objects.filter(UserName__exact=username,PassWord__exact=password)
        if user:
            rq.session['login'] = 'admin'
        else:
            return HttpResponseRedirect('/Index/')
    startPos,endPos,allPage,curPage,pagenum = GetPages(rq)
    article_list = Blogs.objects.all().order_by('-Id')[startPos:endPos]
    type_list = BlogType.objects.all()
    
    return render_to_response('manage.html',{'article_list':article_list,'type_list':type_list,'allPage':allPage,'curPage':curPage,'pagenum':pagenum},context_instance=RequestContext(rq))
import types
def Edit(rq,offset):
    try:
        id = int(offset)
    except ValueError:
        raise Http404()
    try:
        article = Blogs.objects.get(Id=id)
    except Exception:
        article = None
    if article:
        type_list = BlogType.objects.all()
        return render_to_response('edit.html',{'Id':article.Id,'Name':article.Title,'Img':article.Img,'Des':article.Des,'Type':str(article.Type),'Content':article.Content,'type_list':type_list},context_instance=RequestContext(rq))
    else:
        type_list = BlogType.objects.all()
        return render_to_response('edit.html',{'type_list':type_list},context_instance=RequestContext(rq))

def LoginByPwd(rq):
    return render_to_response('login.html', {},context_instance=RequestContext(rq))

def Release(rq):
    articleId = rq.POST.get('articleId','0')
    articleName = rq.POST.get('articleName','')
    articleImg = rq.FILES.get('articleImg', None)
    articleLogo = rq.POST.get('articleLogo','')
    articleDes = rq.POST.get('articleDes','')
    articleType = rq.POST.get('articleType','')
    articleContent = rq.POST.get('articleContent','')
    
    if articleName == '' or articleContent == '':
        return render_to_response('edit.html',{'Id':articleId,'Name':articleName,'Img':articleLogo,'Type':articleType,'Content':articleContent},context_instance=RequestContext(rq))
    else:
        dt = datetime.now()
        imgname = dt.strftime("%Y%m%d%M%H%S{0}{1}".format(random.randint(1,999999),".jpg"))
        imgurl = '/static/upload/' + imgname
        imgpath = 'static/upload/' + imgname
        if articleImg == None:
            if articleLogo == '':
                imgurl = '/static/upload/20160219041029344275.jpg'
            else:
                imgurl = articleLogo
        else:
            uploadUrl = os.path.join(os.path.dirname(__file__),   imgpath).replace('\\','/')
            image = Image.open(articleImg)
            image.save(uploadUrl,"jpeg")
        user = rq.session.get('login','None')
        if user == 'admin':
            try:
                article = Blogs.objects.get(Id=articleId)
            except Exception:
                article = None
            if article:
                article.Title = articleName
                article.Img = imgurl
                article.Des = articleDes
                article.Content = articleContent
                thistype = BlogType.objects.get(Name=articleType)
                if thistype:
                    article.Type = thistype
                article.save()
            else:
                arttype = BlogType.objects.get(Name=articleType)
                newarticle = Blogs(Title=articleName,Img=imgurl,Des=articleDes,Content=articleContent,Type=arttype)
                newarticle.save()
                arttype.Count += 1
                arttype.save()
        
        return HttpResponseRedirect('/Manage/')


def Category(rq,offset):
    try:
        typename = offset
    except ValueError:
        raise Http404()
    startPos,endPos,allPage,curPage,pagenum = GetPages(rq)
    try:
        blogtype = BlogType.objects.filter(Name=typename)
    except:
        raise Http404()
    article_list = Blogs.objects.filter(Type=blogtype).order_by('-Id')[startPos:endPos]
    type_list = BlogType.objects.all()
    
    return render_to_response('index.html',{'article_list':article_list,'type_list':type_list,'allPage':allPage,'curPage':curPage,'pagenum':pagenum},context_instance=RequestContext(rq))

def Admin(rq,offset):
    try:
        typename = offset
    except ValueError:
        raise Http404()
    startPos,endPos,allPage,curPage,pagenum = GetPages(rq)
    try:
        type_id = BlogType.objects.filter(Name=typename)[0].Id
    except:
        raise Http404()
    article_list = Blogs.objects.filter(Type=type_id)[startPos:endPos]
    type_list = BlogType.objects.all()
    
    return render_to_response('manage.html',{'article_list':article_list,'type_list':type_list,'allPage':allPage,'curPage':curPage,'pagenum':pagenum},context_instance=RequestContext(rq))
